//
//  ServiceContact.swift
//  home
//
//  Created by Yun Zeng on 2019/1/31.
//  Copyright © 2019 Yun Zeng. All rights reserved.
//

import UIKit

// 接触式传感器
class ServiceSensorContact {
    var service: Service
    var contactStateChar: HMCharacteristic
    
    init?(service: Service) {
        if service.type != HMServiceType.contactSensor.rawValue {
            return nil
        }
        
        guard let contactChar = service.findCharacteristic(type: .contactSensorState) else {
            return nil
        }
        self.service = service
        self.contactStateChar = contactChar
    }
    
    // 门磁状态
    enum State: Int {
        case detected = 1
        case notDetected = 0
    }
    
    // 显示时间
    var contactState: State {
        if let value = self.contactStateChar.value, let state = State(rawValue: value.toValueInt()!) {
            if state == .notDetected && self.service.state == .online {
                self.service.state = .highlight
            }
            return state
        }
        return .notDetected
    }
}

// 实现单元格显示协议
extension ServiceSensorContact: ServiceCellDelegate {
    var icon: UIView {
        guard  let resource = self.service.icon else {
            return UIView(frame: ServiceCellView.iconSize)
        }
        let imageView = UIImageView(frame: ServiceCellView.iconSize)
        var imgSrc = "service-" + resource + "-close"
        if self.state != .offline && contactState == .notDetected {
            imgSrc = "service-" + resource + "-open"
        }
        imageView.image = UIImage(named: imgSrc)
        return imageView
    }
    
    var room: String {
        if let r = self.service.room {
            return r.name
        }
        return "默认房间"
    }
    
    var name: String {
        if self.service.name != "" {
            return self.service.name
        }
        return "请命名"
    }
    
    var state: Service.State {
        return self.service.state
    }
    
    var desc: String {
        if self.state == .offline {
            return "离线"
        } else if self.state == .update {
            return "正在更细"
        } else {
            if self.contactState == .detected {
                return "关"
            } else {
                return "开"
            }
        }
    }
    
    func toggle() -> HomeAction? {
        return nil
    }
}

